/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rom.factory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import rom.item.Item;

/**
 *
 * @author Luis
 */
public class ItemFactory {

    private ArrayList<Item> items = new ArrayList<>();

    public void addItem(Item item) {
        if (isValid(item)) {
            items.add(item);
        }
    }

    public void removeItem(Item item) {
        if (items.contains(item)) {
            items.remove(item);
        }
    }

    public Item getItem(int id) {
        for (Item item : items) {
            if (item.getId() == id) {
                return item;
            }
        }
        return null;
    }

    public Item getItem(String name) {
        for (Item item : items) {
            if (item.geteName().equals(name)) {
                return item;
            }
        }
        return null;
    }

    public Boolean isValid(Item item) {
        for (Item i : items) {
            if (i.getId() == item.getId()) {
                return false;
            }
        }
        return true;
    }

    public int size() {
        return items.size();
    }

    public void saveItem(Item item, File file) throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) {
            oos.writeObject(item);
            oos.flush();
        }
    }

    public Item readItem(File file) throws FileNotFoundException, IOException, ClassNotFoundException {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
            Object aux = ois.readObject();

            while (aux != null) {
                if (aux instanceof Item) {
                    return (Item) aux;
                }
            }
        }
        return null;
    }
}
